﻿import type {RequestOptions} from '@@/plugin-request/request';
import type {RequestConfig} from '@umijs/max';
import {message} from "antd";
import axios from "axios";
import {history, useModel} from "@@/exports";

// 错误处理方案： 错误类型
enum ErrorShowType {
    SILENT = 0,
    WARN_MESSAGE = 1,
    ERROR_MESSAGE = 2,
    NOTIFICATION = 3,
    REDIRECT = 9,
}

// 与后端约定的响应数据格式
interface ResponseStructure {
    success: boolean;
    data: any;
    errorCode?: number;
    errorMessage?: string;
    showType?: ErrorShowType;
}

/**
 * @name 错误处理
 * pro 自带的错误处理， 可以在这里做自己的改动
 * @doc https://umijs.org/docs/max/request#配置
 */
export const requestConfig: RequestConfig = {
    baseURL: process.env.NODE_ENV == 'development' ? 'http://127.0.0.1:8101' : 'http://api-hub.xn--torp68ch8h18h1jp.top',
    withCredentials: true,
    // 请求拦截器
    requestInterceptors: [
        (config: RequestOptions) => {
            const token = localStorage.getItem("token");
            const url = config?.url;
            config.headers['Authorization'] = token || '';

            // 判断是否是第三方回调登录
            const {location} = history;
            if (location.pathname == "/") {
                const indexUrl = new URL(window.location.href);
                const urlParams = indexUrl.searchParams;
                const token = urlParams.get('token');
                indexUrl.search = '';
                if (token) {
                    // 是第三方回调登录，则需要设置token
                    config.headers['Authorization'] = token || '';
                    localStorage.setItem("token", token);
                    message.success("登录成功")
                }
                // 更新浏览器URL
                window.history.pushState(null, '', indexUrl.toString());
                return {...config, indexUrl};
            }

            return {...config, url};
        },
    ],

    // 响应拦截器
    responseInterceptors: [
        (response) => {
            // 拦截响应数据，进行个性化处理
            const {data} = response as unknown as ResponseStructure;
            // if (data.code !== 2000) {
            //     message.error(data.message).then(r => {
            //     })
            // }
            const token = data.data?.token;
            if (token) {
                localStorage.setItem("token", token);
            }
            return response;
        },
    ],
};
